package org.meetunexpectedly.controller.middleground;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.meetunexpectedly.authority.Authority;
import org.meetunexpectedly.config.LocalCache;
import org.meetunexpectedly.entity.json.SettingScoreJson;
import org.meetunexpectedly.entity.setting.Setting;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.service.setting.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 管理系统设置控制器
 * @Author: pupil
 * @Date: 2024/09/05 下午 8:15
 */
@RestController
@RequestMapping("/admin/setting")
public class AdminSettingController {

    @Autowired
    private SettingService settingService;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取系统设置
     * @return
     */
    @GetMapping
    @Authority("admin:setting:get")
    public Result getSetting() throws JsonProcessingException {
        Setting setting = settingService.list(null).get(0);
        SettingScoreJson settingScoreJson = objectMapper.readValue(setting.getAuditPolicy(), SettingScoreJson.class);
        setting.setSettingScoreJson(settingScoreJson);

        return Result.ok().data(setting);
    }

    /**
     * 更新系统设置
     * @param setting
     * @return
     */
    @PutMapping
    @Authority("admin:setting:update")
    public Result updateSetting(@RequestBody @Validated Setting setting){
        if (!settingService.updateById(setting)){
            return Result.error().message("修改失败");
        }

        for (String s : setting.getAllowIp().split(",")) {
            LocalCache.put(s,true);
        }

        return Result.ok().message("修改成功");
    }
}
